﻿module Sustainalytics.Screening {

    import Common = Sustainalytics.Common;

    export class TemplateCriteriaService implements ITemplateCriteriaService {

        private urlBase: string;

        constructor(
            private $q: ng.IQService,
            private $http: ng.IHttpService,
            private $location: ng.ILocationService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private $rootScope: ng.IScope) {

            this.urlBase = staticObjects.screeningToolBaseUrl;
        }

        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err['code']));
        }

        //#region URL
        private templateCriteriaUrl(criteriaLevel1Id?: string, criteriaLevel2Id?: string, criteriaLevel3Id?: string, templateId?: string): string {
            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port() +
                this.staticObjects.screeningToolServBaseUrl + "/criterialevel1/" + criteriaLevel1Id +
                "/criterialevel2/" + criteriaLevel2Id + "/criterialevel3/" + criteriaLevel3Id + "/templatecriteria" + ((templateId) ? "/" + templateId : "");;
        }

        private criteriaUrl(id?: string): string {

            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port() + this.staticObjects.screeningToolServBaseUrl
                + "/criteria/" + ((id) ? id : "");
        }

        //screeningtoolserv/api/v1/filters/{filterid}/criteria/{criteriaid?}
        private filterCriteriaUrl(filterid: string, id?: string): string {

            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port() + this.staticObjects.screeningToolServBaseUrl
                + "/filters/" + filterid + "/criteria/" + ((id) ? id : "");
        }

        private productInvolvementUrl(symbol: string) {
            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port() + "/productinvolvementserv/api/v1/piindicator/" + symbol + "/categories";
        }
        //#endregion

        public listTemplateCriteriaByLevel3Id(criteriaLevel3Id: string) {
            var ctx = this;
            return this.$http.get(ctx.templateCriteriaUrl(null, null, criteriaLevel3Id));
        }

        //#region loadCriteriaType
        public loadCriteriaTypeOne(criteriaTemplateId) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaTemplateId), { params: { CriteriaType: 1, isTemplate: true } });
        }

        public loadCriteriaTypeTwo(criteriaTemplateId) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaTemplateId), { params: { CriteriaType: 2, isTemplate: true } });
        }

        public loadCriteriaTypeThree(criteriaId, skip, take) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaId), { params: { CriteriaType: 3, skip: skip, take: take } });
        }

        public loadCriteriaTypeFourCategories(symbol) {
            return this.$http.get(this.productInvolvementUrl(symbol));
        }

        public loadCriteriaTypeFour(piFilterCriteriaId: string, filterId: string) {
            var ctx = this;
            return this.$http.get(this.filterCriteriaUrl(filterId, piFilterCriteriaId), { params: { CriteriaType: 4 } });
        }

        public loadCriteriaTypeFive(criteriaId) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaId),
                { params: { CriteriaType: 5 } });
        }

        public loadTemplateCriteriaTypeFive(criteriaTemplateId) {
            var ctx = this;
            return this.$http.get(this.criteriaUrl(criteriaTemplateId), { params: { CriteriaType: 5, isTemplate: true } });
        }

        public loadCriteriaType25(criteriaId) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaId),
                { params: { CriteriaType: 25 } });
        }

        public loadTemplateCriteriaType25(criteriaTemplateId) {
            var ctx = this;
            return this.$http.get(this.criteriaUrl(criteriaTemplateId), { params: { CriteriaType: 25, isTemplate: true } });
        }

        public loadCriteriaTypeSix(criteriaTemplateId: string) {
            var ctx = this;
            return this.$http.get(this.criteriaUrl(criteriaTemplateId), { params: { CriteriaType: 6, isTemplate: true } });
        }

        public loadCriteriaTypeSeven(criteriaId, skip, take) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaId), { params: { CriteriaType: 7, skip: skip, take: take } });
        }

        public loadCriteriaType16(criteriaTemplateId) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaTemplateId), { params: { CriteriaType: 16, isTemplate: true } });
        }
        //#endregion

        public getCriteriaTypeThreeCollectionItems(criteriaId, filter, loadMore, skip, take) {
            var ctx = this;
            return this.$http.get(ctx.criteriaUrl(criteriaId), { params: { CriteriaType: 3, skip: skip, take: take, searchText: filter, loadMore: loadMore } });
        }

        public composeAnswerText(arrAnswers, score) {
            if (arrAnswers) {
                var list = arrAnswers;
                if (score != null) {
                    //filter  by score
                    list = arrAnswers.filter((elem) => { return elem.score == score; });
                }
                // sort by score 
                var sorted = list.sort((a, b) => { return a.score - b.score; });
                return this.composeAnswers(sorted);
            }
            return "";
        }

        private composeAnswers(arrAnswers: any): string {
            var result = "Minimum threshold is set to: ";

            if (arrAnswers.length === 1 && arrAnswers[0].score === -1)
                return "";

            arrAnswers.forEach((item, index) => {

                var text = item.text[0].toLowerCase() + item.text.substring(1);
                if (index == 0)
                    result += text;
                else
                    result += " or " + text;
            });

            result += ".";
            return result;
        }

        public loadDataPointsForReport(criteriaLevel2Id: string, listChecks: any) {
            var ctx = this;
            var def = this.$q.defer();

            var url = ctx.criteriaUrl(null);
            var newList = new Array();

            for (var i = 0; i < listChecks.length; i++) {
                var currentItem = angular.toJson(listChecks[i]);
                newList.push(currentItem);
            }
            console.log(newList);

            var params = $.param({
                criteriaLevel2Id: criteriaLevel2Id
            });
            console.log(params);
            var promise: ng.IHttpPromise< {}> = this.$http({
                method: "POST",
                url: url + "?" + params,
                data: newList
            });
            return promise;
        }

    }
    var mod = angular.module(screeningToolModuleName);

    mod.service('templateCriteriaService',
        ['$q', '$http', '$location', 'notificationFactory', 'staticObjects', '$rootScope', TemplateCriteriaService]);
}